var needle = require('needle')
  , logger = require('./Logger')
  , User = require('../proxy').User
  , redisManager = require('../proxy').RedisManager
  , config = require('../config').config;
/**
 * 验证是否是取得授权的用户
 */
exports.checkAuth = function(req, res, next){
	var cookie_openId = req.cookies.fj_wechat;
	console.log('------------cookie--------------\n'+cookie_openId);
	if(cookie_openId){
        req.params.openId = cookie_openId;
        req.body.openId = cookie_openId;
        redisManager.getUser(cookie_openId, function(err, user){
           if(user){
               req.params.currentUser = user;
               res.locals.currentUser = user;
               //req.body.openId = user;
               next();
           }else{
               //从mongo里拿到
               User.getUserByOpenId(cookie_openId, function(err, user){
                   redisManager.putUserIntoCache(user, function(err, data){
                       req.params.currentUser = user;
                       res.locals.currentUser = user;
                       //req.body.openId = user;
                       next();
                   })
               })
           }
        })
    }else{
		// 请求OAuth2.0授权
		var userAgent = req.headers['user-agent'];
        var origUrl = encodeURIComponent(req.originalUrl);
		// redirect_uri中用http考虑兼容iphone，https只能在Android下有效，iphone无法跳转
		var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            +config.wechat_appid+'&redirect_uri='+config.wechat_url
            +'oauth2cb&response_type=code&scope=snsapi_userinfo&state=';
		url += origUrl
		if(/Android/.test(userAgent)){
			url += '#wechat_redirect';
		}else{
			url += '#wechat_redirect';
		}
		res.redirect(url);
	}
}

exports.oauth2cb = function (req, res, next){
	var code = req.query.code
	  , state = req.query.state
	if(code && code !=='authdeny'){
		_getOAuthAccToken(code, function(err, data){
            var openId = data.openid;
            if(!err && openId){
                var acctoken = data.access_token;
                res.cookie('fj_wechat', openId, {maxAge:6000000*24*20, httpOnly:true, path:'/', secure:false});
                logger.debug('Customer :['+openId+'] OAuth2.0 passed !');
                //if is already registed user
                User.getUserByOpenId(openId, function(err, user){
                    if(user){
                        return res.redirect(state);
                    }else{
                        // get wechat user info
                        _fetchUserInfo(acctoken, openId, function(err, data){
                            var name = data.nickname,
                                openid = data.openid,
                                gender = data.sex == '1'?'male':'female',
                                city = data.city,
                                province = data.province,
                                country = data.country,
                                headimg = data.headimgurl;
                            User.newAndSave(name, gender, city, province, country, openid, headimg, function(err, user){
                                if(err){
                                    logger.error(err.message);
                                    return res.render('others/error', {msg: err})
                                }
                                // 此处可以带上user信息后重定向
                                res.locals.currentUser = user;
                                return res.redirect(state);
                            })
                        })
                    }
                })
            }else{
                res.render('others/error', {msg:'获取授权信息失败,请重新关注再试试吧~'});
            }
		})
	}else{
		res.redirect('/others/oauthCancel.html');
	}
}

/**
 * 无确认页面OAuth授权
 * @param req
 * @param res
 * @param next
 * @returns {*}
 * @constructor
 */
exports.OAuth2WithoutPage = function(req, res, next){
    if(req.query.code){
        return next();
    }else{
        var orgiUrl = encodeURIComponent('http://wechatjh.fourjoy.net' + req.url);
        var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            +config.wechat_appid+'&redirect_uri='+orgiUrl+'&response_type=code&scope=snsapi_base&state=addressJsApi';
        res.redirect(url);
    }
}

/**
 * 用授权code拿到access_token
 * @param code
 * @param callback
 * @private
 */
function _getOAuthAccToken(code, callback){
	var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
            +config.wechat_appid+'&secret='+config.wechat_secret+'&code='+code+'&grant_type=authorization_code';
    var option = {headers: {'Content-Type': 'application/json'}, decode:false}
	needle.get(url, option, function(err, resp, body){
        callback(err, JSON.parse(body));
	});
}
/**
 * 根据授权access_token拿到用户信息
 * @param acctoken
 * @param openid
 * @param callback
 * @private
 */
function _fetchUserInfo(acctoken, openid, callback){
    var url = 'https://api.weixin.qq.com/sns/userinfo?access_token='+acctoken+'&openid='+openid+'&lang=zh_CN';
    var option = {headers: {'Content-Type': 'application/json'}, decode:false}
    needle.get(url, option, function(err, resp, body){
        logger.debug(body);
        callback(err, JSON.parse(body));//TODO: [SyntaxError: Unexpected token u]
    })
}